package com.onlinelibrary.util;

import com.onlinelibrary.mapper.BookMapper;
import com.onlinelibrary.pojo.Book;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Item;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

@RequiredArgsConstructor
@Component
public class MinioUtil {

    //minio
    private final MinioClient minioClient;


    //传入文件，文件名，存储桶名
    //返回路径
    public String addDataInBucket(MultipartFile file, String fileName, String bucketName) {
        try {
            //解读文件对象，拿到后缀
            String originalFilename = file.getOriginalFilename();
            String hz = null;
            if (originalFilename != null) {
                hz = originalFilename.substring(originalFilename.lastIndexOf('.'));
            }
            String headUrl;
            //将头像以id+后缀的形式放入存储桶内
            ObjectWriteResponse book = minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName + hz)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build()
            );
            //获取该头像路径
            headUrl = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName)
                    .object(fileName + hz)
                    .method(Method.GET)
                    .build()
            );
            return headUrl;
        } catch (Exception e) {
            return null;
        }
    }

    public List<String> getTopImg() {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket("fengmian").build()
        );
        ArrayList<String> list=new ArrayList<>();
        results.forEach(itemResult -> {
            try {
                String s = "http://127.0.0.1:9000/fengmian/" + itemResult.get().objectName();
                list.add(s);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return list;

    }

    private final BookMapper bookMapper;
//    public boolean updateCoverImage() {
//        List<Book> list = bookMapper.list();
//        List<String> isbns=new ArrayList<>();
//        for (Book book : list) {
//            isbns.add(book.getIsbn());
//        }
//        minioClient.getObject(new GetObjectArgs())
//
//    }
}
